/*
 * @Author: 余其方 448919239@qq.com
 * @Date: 2022-08-02 20:22:38
 * @LastEditors: 余其方 448919239@qq.com
 * @LastEditTime: 2022-11-01 20:03:08
 * @FilePath: /redux-demo/src/App.jsx
 * @Description:
 */
import React, { useState, useEffect } from "react";
import ToDoListUI from "./components/ToDoListUI";
import {
  getInputChangeAction,
  getButClickAction,
  getDeleteItem,
  getTodoList,
  getInitList,
} from "./store/actionCreators";
import "antd/dist/antd.min.css";
// import utc2beijing from "./utils/utc2beijing";
// import getUrlParams from "./utils/getUrlParams";
// import replaceStr from "./utils/replaceStr";
// import useWinSize from "./hooks/useWinSize";
import { store } from "./store";
// import axios from "axios";

const App = () => {
  const [state, setState] = useState(store.getState());

  useEffect(() => {
    // redux-thunk 处理异步
    // 使用了 redux-thunk 之后就可以 dispatch 一个函数给 store 了，该函数会立即自动执行并会接收一个 dispatch 方法
    // const action = getTodoList();
    // store.dispatch(action);

    // redux-sage 处理异步
    const action = getInitList();
    store.dispatch(action);
    /*
      从文件./store/actionCreators中的getInitList()返回的内容为: 
      ({
        type: GET_INIT_LIST,
      })

      type: GET_INIT_LIST进而匹配到./sagas.js中的yield takeEvery(GET_INIT_LIST, initListFn);
    */
  }, []);

  // 订阅 store 的改变，只要 store 一改变，就执行回调
  useEffect(() => {
    store.subscribe(() => {
      setState(store.getState()); // 把新的 store.getState() 数据赋值给state
    });
  }, []);

  // 输入框回调
  const inputChange = (e) => {
    const action = getInputChangeAction(e.target.value);
    store.dispatch(action); // 分发 action 给 store，然后 store 交给 reducer 去处理
  };

  // 提交保存这条todo
  const butClick = () => {
    const action = getButClickAction();
    store.dispatch(action);
  };

  // 删除todo
  const deleteItem = (index) => {
    const action = getDeleteItem(index);
    store.dispatch(action);
  };

  return (
    <ToDoListUI
      inputValue={state.inputValue}
      list={state.list}
      inputChange={inputChange}
      butClick={butClick}
      deleteItem={deleteItem}
    />
  );
};
export default App;
